package com.kakarote.hrm.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.core.common.MultipartFileUtil;
import com.kakarote.core.common.Result;
import com.kakarote.core.common.cache.AdminCacheKey;
import com.kakarote.core.common.enums.FieldEnum;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.UploadEntity;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.service.AdminFileService;
import com.kakarote.core.redis.Redis;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.ExcelParseUtil;
import com.kakarote.hrm.entity.BO.QueryRecruitStartPositionPageListBO;
import com.kakarote.hrm.entity.PO.HrmRecruitPlan;
import com.kakarote.hrm.entity.PO.HrmRecruitPlanRecord;
import com.kakarote.hrm.entity.PO.HrmRecruitPosition;
import com.kakarote.hrm.entity.PO.HrmRecruitStartPosition;
import com.kakarote.hrm.entity.VO.RecruitPlanRecordVO;
import com.kakarote.hrm.entity.VO.RecruitPositionVO;
import com.kakarote.hrm.entity.VO.RecruitStartPositionExportVO;
import com.kakarote.hrm.entity.VO.RecruitStartPositionVO;
import com.kakarote.hrm.mapper.HrmRecruitStartPositionMapper;
import com.kakarote.hrm.service.IHrmRecruitPlanRecordService;
import com.kakarote.hrm.service.IHrmRecruitPlanService;
import com.kakarote.hrm.service.IHrmRecruitPositionService;
import com.kakarote.hrm.service.IHrmRecruitStartPositionService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 招聘启动岗位 服务实现类
 * </p>
 *
 * @author system
 * @since 2024-01-01
 */
@Service
public class HrmRecruitStartPositionServiceImpl extends BaseServiceImpl<HrmRecruitStartPositionMapper, HrmRecruitStartPosition> implements IHrmRecruitStartPositionService {

    @Autowired
    private HrmRecruitStartPositionMapper recruitStartPositionMapper;
    @Autowired
    private HrmRecruitPlanRecordServiceImpl hrmRecruitPlanRecordService;
    @Autowired
    private IHrmRecruitPlanService hrmRecruitPlanService;
    @Autowired
    private IHrmRecruitPositionService hrmRecruitPositionService;
    @Autowired
    private Redis redis;
    @Resource
    private AdminFileService adminFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog addRecruitStartPosition(HrmRecruitStartPosition recruitStartPosition) {
        RecruitPlanRecordVO recruitPlanRecordVO = hrmRecruitPlanRecordService.queryById(recruitStartPosition.getRecordId());
        if (recruitPlanRecordVO == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "计划记录不存在");
        }
        recruitStartPosition.setPlanId(recruitPlanRecordVO.getPlanId());
        save(recruitStartPosition);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recruitStartPosition.getStartPositionId(), "招聘启动岗位");
        String detail = String.format("计划编号：%s，记录编号：%s，岗位编号：%s，招聘数量：%d，联系人：%s",
                recruitStartPosition.getPlanId() != null ? recruitStartPosition.getPlanId().toString() : "无",
                recruitStartPosition.getRecordId() != null ? recruitStartPosition.getRecordId().toString() : "无",
                recruitStartPosition.getPositionId() != null ? recruitStartPosition.getPositionId().toString() : "无",
                recruitStartPosition.getPositionNum() != null ? recruitStartPosition.getPositionNum() : 0,
                StrUtil.isNotEmpty(recruitStartPosition.getContactUser()) ? recruitStartPosition.getContactUser() : "无");
        operationLog.setOperationInfo(detail);
        operationLog.setBehavior(BehaviorEnum.SAVE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog setRecruitStartPosition(HrmRecruitStartPosition recruitStartPosition) {
        HrmRecruitStartPosition oldPosition = getById(recruitStartPosition.getStartPositionId());
        if (oldPosition == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "招聘启动岗位不存在");
        }
        if (recruitStartPosition.getRecordId() != null) {
            RecruitPlanRecordVO recruitPlanRecordVO = hrmRecruitPlanRecordService.queryById(recruitStartPosition.getRecordId());
            if (recruitPlanRecordVO == null) {
                throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "计划记录不存在");
            }
            recruitStartPosition.setPlanId(recruitPlanRecordVO.getPlanId());
        } else {
            recruitStartPosition.setPlanId(null);
        }

        // 记录变更内容
        StringBuilder detail = new StringBuilder();
        if (!Objects.equals(oldPosition.getPlanId(), recruitStartPosition.getPlanId())) {
            detail.append(String.format("计划编号：%s → %s；",
                    oldPosition.getPlanId() != null ? oldPosition.getPlanId().toString() : "无",
                    recruitStartPosition.getPlanId() != null ? recruitStartPosition.getPlanId().toString() : "无"));
        }
        if (!Objects.equals(oldPosition.getRecordId(), recruitStartPosition.getRecordId())) {
            detail.append(String.format("记录编号：%s → %s；",
                    oldPosition.getRecordId() != null ? oldPosition.getRecordId().toString() : "无",
                    recruitStartPosition.getRecordId() != null ? recruitStartPosition.getRecordId().toString() : "无"));
        }
        if (!Objects.equals(oldPosition.getPositionId(), recruitStartPosition.getPositionId())) {
            detail.append(String.format("岗位编号：%s → %s；",
                    oldPosition.getPositionId() != null ? oldPosition.getPositionId().toString() : "无",
                    recruitStartPosition.getPositionId() != null ? recruitStartPosition.getPositionId().toString() : "无"));
        }
        if (!Objects.equals(oldPosition.getPositionNum(), recruitStartPosition.getPositionNum())) {
            detail.append(String.format("招聘数量：%d → %d；",
                    oldPosition.getPositionNum() != null ? oldPosition.getPositionNum() : 0,
                    recruitStartPosition.getPositionNum() != null ? recruitStartPosition.getPositionNum() : 0));
        }
        if (!Objects.equals(oldPosition.getPositionDuty(), recruitStartPosition.getPositionDuty())) {
            detail.append(String.format("岗位职责：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getPositionDuty()) ? oldPosition.getPositionDuty() : "无",
                    StrUtil.isNotEmpty(recruitStartPosition.getPositionDuty()) ? recruitStartPosition.getPositionDuty() : "无"));
        }
        if (!Objects.equals(oldPosition.getConditionRequire(), recruitStartPosition.getConditionRequire())) {
            detail.append(String.format("条件要求：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getConditionRequire()) ? oldPosition.getConditionRequire() : "无",
                    StrUtil.isNotEmpty(recruitStartPosition.getConditionRequire()) ? recruitStartPosition.getConditionRequire() : "无"));
        }
        if (!Objects.equals(oldPosition.getSalary(), recruitStartPosition.getSalary())) {
            detail.append(String.format("薪资待遇：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getSalary()) ? oldPosition.getSalary() : "无",
                    StrUtil.isNotEmpty(recruitStartPosition.getSalary()) ? recruitStartPosition.getSalary() : "无"));
        }
        if (!Objects.equals(oldPosition.getWorkLocation(), recruitStartPosition.getWorkLocation())) {
            detail.append(String.format("工作地点：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getWorkLocation()) ? oldPosition.getWorkLocation() : "无",
                    StrUtil.isNotEmpty(recruitStartPosition.getWorkLocation()) ? recruitStartPosition.getWorkLocation() : "无"));
        }
        if (!Objects.equals(oldPosition.getContactUser(), recruitStartPosition.getContactUser())) {
            detail.append(String.format("联系人：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getContactUser()) ? oldPosition.getContactUser() : "无",
                    StrUtil.isNotEmpty(recruitStartPosition.getContactUser()) ? recruitStartPosition.getContactUser() : "无"));
        }
        if (!Objects.equals(oldPosition.getContactPhone(), recruitStartPosition.getContactPhone())) {
            detail.append(String.format("联系电话：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getContactPhone()) ? oldPosition.getContactPhone() : "无",
                    StrUtil.isNotEmpty(recruitStartPosition.getContactPhone()) ? recruitStartPosition.getContactPhone() : "无"));
        }

        updateById(recruitStartPosition);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recruitStartPosition.getStartPositionId(), "招聘启动岗位");
        operationLog.setOperationInfo(detail.toString());
        operationLog.setBehavior(BehaviorEnum.UPDATE);
        return operationLog;
    }

    @Override
    public RecruitStartPositionVO queryById(Long startPositionId) {
        return recruitStartPositionMapper.queryById(startPositionId);
    }

    @Override
    public BasePage<RecruitStartPositionVO> queryRecruitStartPositionPageList(QueryRecruitStartPositionPageListBO queryRecruitStartPositionPageListBO) {
        BasePage<RecruitStartPositionVO> page = queryRecruitStartPositionPageListBO.parse();
        return recruitStartPositionMapper.queryRecruitStartPositionPageList(page, queryRecruitStartPositionPageListBO);
    }

    @Override
    public List<RecruitStartPositionVO> queryByPlanId(Long planId) {
        return recruitStartPositionMapper.queryByPlanId(planId);
    }

    @Override
    public List<RecruitStartPositionVO> queryByRecordId(Long recordId) {
        return recruitStartPositionMapper.queryByRecordId(recordId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteRecruitStartPosition(Long startPositionId) {
        HrmRecruitStartPosition position = getById(startPositionId);
        if (position == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "招聘启动岗位不存在");
        }

        removeById(startPositionId);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(startPositionId, "招聘启动岗位");
        operationLog.setOperationInfo(String.format("删除招聘启动岗位，计划编号：%s，岗位编号：%s",
                position.getPlanId() != null ? position.getPlanId().toString() : "无",
                position.getPositionId() != null ? position.getPositionId().toString() : "无"));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog batchDeleteRecruitStartPosition(List<Long> startPositionIds) {
        if (startPositionIds == null || startPositionIds.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "请选择要删除的岗位");
        }

        List<HrmRecruitStartPosition> positions = listByIds(startPositionIds);
        if (positions.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "选择的岗位不存在");
        }

        removeByIds(startPositionIds);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(startPositionIds.toString(), "批量删除招聘启动岗位");
        StringBuilder detail = new StringBuilder("删除岗位：");
        for (HrmRecruitStartPosition position : positions) {
            detail.append("岗位ID:").append(position.getStartPositionId()).append("、");
        }
        if (detail.length() > 0) {
            detail.setLength(detail.length() - 1);
        }
        operationLog.setOperationInfo(detail.toString());
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteByPlanId(Long planId) {
        Map<String, Object> params = new HashMap<>();
        params.put("plan_id", planId);
        List<HrmRecruitStartPosition> positions = listByMap(params);
        if (!positions.isEmpty()) {
            recruitStartPositionMapper.deleteByPlanId(planId);
        }

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(planId, "删除计划下所有启动岗位");
        operationLog.setOperationInfo(String.format("删除计划下所有启动岗位，共%d个", positions.size()));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteByRecordId(Long recordId) {
        Map<String, Object> params = new HashMap<>();
        params.put("record_id", recordId);
        List<HrmRecruitStartPosition> positions = listByMap(params);
        if (!positions.isEmpty()) {
            recruitStartPositionMapper.deleteByRecordId(recordId);
        }

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recordId, "删除记录下所有启动岗位");
        operationLog.setOperationInfo(String.format("删除记录下所有启动岗位，共%d个", positions.size()));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    public void exportRecruitStartPosition(HttpServletResponse response, QueryRecruitStartPositionPageListBO queryRecruitStartPositionPageListBO) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = "招聘启动岗位_" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

        // 直接查询所有符合条件的数据（不分页）
        List<RecruitStartPositionVO> dataList = recruitStartPositionMapper.queryAllRecruitStartPositionList(queryRecruitStartPositionPageListBO);

        // 转换为导出VO
        List<RecruitStartPositionExportVO> exportList = new ArrayList<>();
        for (RecruitStartPositionVO vo : dataList) {
            RecruitStartPositionExportVO exportVO = new RecruitStartPositionExportVO();
            exportVO.setPlanName(vo.getPlanName());
            exportVO.setRecordCode(vo.getRecordCode());
            exportVO.setPositionName(vo.getPositionName());
            exportVO.setPositionCode(vo.getPositionCode());
            exportVO.setPositionUnit(vo.getPositionUnit());
            exportVO.setPositionNum(vo.getPositionNum());
            exportVO.setPositionDuty(vo.getPositionDuty());
            exportVO.setConditionRequire(vo.getConditionRequire());
            exportVO.setSalary(vo.getSalary());
            exportVO.setWorkLocation(vo.getWorkLocation());
            exportVO.setContactUser(vo.getContactUser());
            exportVO.setContactPhone(vo.getContactPhone());
            exportVO.setCreateTime(vo.getCreateTime());
            exportVO.setCreateRealName(vo.getCreateRealName());
            exportList.add(exportVO);
        }

        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), RecruitStartPositionExportVO.class)
                .sheet("招聘启动岗位")
                .doWrite(exportList);
    }

    @Override
    public void downloadExcel(HttpServletResponse response) {
        List<JSONObject> list = queryField();
        ExcelParseUtil.importExcel(new ExcelParseUtil.ExcelParseService() {
            @Override
            public String getExcelName() {
                return "招聘启动岗位";
            }

            @Override
            public String getMergeContent(String module) {
                return "注意事项：\n" +
                        "1、表头标“*”的红色字体为必填项\n" +
                        "2、导入只新增不修改\n" +
                        "3、计划名称和计划编号必须已存在\n" +
                        "4、记录编号必须已存在\n" +
                        "5、岗位名称和岗位编号必须已存在\n" +
                        "6、招聘数量必须大于0\n";
            }
        }, list, response, "user");
    }

    private List<JSONObject> queryField() {
        List<JSONObject> list = new ArrayList<>();
        list.add(queryField("planName", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "计划名称", 1));
        list.add(queryField("planCode", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "计划编号", 1));
        list.add(queryField("recordCode", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "记录编号", 1));
        list.add(queryField("positionName", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "岗位名称", 1));
        list.add(queryField("positionCode", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "岗位编号", 1));
        list.add(queryField("positionNum", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "招聘数量", 1));
        list.add(queryField("positionDuty", FieldEnum.TEXTAREA.getFormType(), FieldEnum.TEXTAREA.getType(), "岗位职责", 0));
        list.add(queryField("conditionRequire", FieldEnum.TEXTAREA.getFormType(), FieldEnum.TEXTAREA.getType(), "条件要求", 0));
        list.add(queryField("salary", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "薪资待遇", 0));
        list.add(queryField("workLocation", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "工作地点", 0));
        list.add(queryField("contactUser", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "联系人", 0));
        list.add(queryField("contactPhone", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "联系电话", 0));
        return list;
    }

    private JSONObject queryField(String fieldName, String formType, Integer type, String name, Integer isNull) {
        JSONObject json = new JSONObject();
        json.fluentPut("fieldName", fieldName)
                .fluentPut("formType", formType)
                .fluentPut("type", type)
                .fluentPut("name", name).fluentPut("isNull", isNull);
        return json;
    }

    private String getFilePath(MultipartFile file) {
        String dirPath = FileUtil.getTmpDirPath();
        try {
            InputStream inputStream = file.getInputStream();
            File fromStream = FileUtil.writeFromStream(inputStream, dirPath + "/" + IdUtil.simpleUUID() + file.getOriginalFilename());
            return fromStream.getAbsolutePath();
        } catch (IOException e) {
            throw new CrmException(SystemCodeEnum.SYSTEM_UPLOAD_FILE_ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject excelImport(MultipartFile file) {
        List<List<Object>> errList = new ArrayList<>();
        String filePath = getFilePath(file);
        AtomicReference<Integer> num = new AtomicReference<>(0);
        //新增启动岗位
        List<HrmRecruitStartPosition> addStartPositionList = new ArrayList<>();
        //查询所有招聘计划
        List<HrmRecruitPlan> planList = hrmRecruitPlanService.list();
        Map<String, HrmRecruitPlan> planMap;
        if (planList != null && !planList.isEmpty()) {
            planMap = planList.stream().collect(Collectors.toMap(item -> Optional.ofNullable(item.getPlanName()).orElse("") + Optional.ofNullable(item.getPlanCode()).orElse(""), Function.identity(), (v1, v2) -> v1));
        } else {
            planMap = new HashMap<>();
        }
        //查询所有招聘记录
        List<HrmRecruitPlanRecord> recordList = hrmRecruitPlanRecordService.list();
        Map<String, HrmRecruitPlanRecord> recordMap;
        if (recordList != null && !recordList.isEmpty()) {
            recordMap = recordList.stream().collect(Collectors.toMap(HrmRecruitPlanRecord::getRecordCode, Function.identity(), (v1, v2) -> v1));
        } else {
            recordMap = new HashMap<>();
        }
        //查询所有招聘岗位
        List<HrmRecruitPosition> positionList = hrmRecruitPositionService.list();
        Map<String, HrmRecruitPosition> positionMap;
        if (positionList != null && !positionList.isEmpty()) {
            positionMap = positionList.stream().collect(Collectors.toMap(item -> {
                Long planId = Optional.ofNullable(item.getPlanId()).orElse(0L);
                String name = Optional.ofNullable(item.getPositionName()).orElse("");
                String code = Optional.ofNullable(item.getPositionCode()).orElse("");
                return planId + "_" + name + "_" + code;
            }, Function.identity(), (v1, v2) -> v1));
        } else {
            positionMap = new HashMap<>();
        }

        ExcelUtil.readBySax(filePath, 0, (int sheetIndex, long rowIndex, List<Object> rowList) -> {
            if (rowIndex > 1) {
                num.getAndSet(num.get() + 1);
                if (rowList.size() < 12) {
                    int size = rowList.size();
                    for (int i = 0; i < 12 - size; i++) {
                        rowList.add("");
                    }
                }
                // 验证必填字段
                if (StrUtil.isEmptyIfStr(rowList.get(0).toString().trim())) {
                    rowList.add(0, "计划名称不能为空");
                    errList.add(rowList);
                    return;
                }
                if (StrUtil.isEmptyIfStr(rowList.get(1).toString().trim())) {
                    rowList.add(0, "计划编号不能为空");
                    errList.add(rowList);
                    return;
                }

                String planKey = rowList.get(0).toString().trim() + rowList.get(1).toString().trim();
                if (!planMap.containsKey(planKey)) {
                    rowList.add(0, "计划不存在");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitPlan plan = planMap.get(planKey);
                if (plan == null) {
                    rowList.add(0, "计划不存在");
                    errList.add(rowList);
                    return;
                }

                // 验证记录编号
                if (StrUtil.isEmptyIfStr(rowList.get(2).toString().trim())) {
                    rowList.add(0, "记录编号不能为空");
                    errList.add(rowList);
                    return;
                }

                String recordCode = rowList.get(2).toString().trim();
                if (!recordMap.containsKey(recordCode)) {
                    rowList.add(0, "记录不存在");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitPlanRecord record = recordMap.get(recordCode);
                if (record == null) {
                    rowList.add(0, "记录不存在");
                    errList.add(rowList);
                    return;
                }

                // 验证记录是否属于该计划
                if (!Objects.equals(record.getPlanId(), plan.getPlanId())) {
                    rowList.add(0, "记录不属于该计划");
                    errList.add(rowList);
                    return;
                }

                // 验证岗位名称
                if (StrUtil.isEmptyIfStr(rowList.get(3).toString().trim())) {
                    rowList.add(0, "岗位名称不能为空");
                    errList.add(rowList);
                    return;
                }

                // 验证岗位编号
                if (StrUtil.isEmptyIfStr(rowList.get(4).toString().trim())) {
                    rowList.add(0, "岗位编号不能为空");
                    errList.add(rowList);
                    return;
                }
                String positionCode = rowList.get(4).toString().trim();

                String positionName = rowList.get(3).toString().trim();
                String positionKey = plan.getPlanId() + "_" + positionName + "_" + positionCode;
                if (!positionMap.containsKey(positionKey)) {
                    rowList.add(0, "岗位不存在");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitPosition position = positionMap.get(positionKey);
                if (position == null) {
                    rowList.add(0, "岗位不存在");
                    errList.add(rowList);
                    return;
                }
                if (!Objects.equals(Optional.ofNullable(position.getPositionCode()).orElse(""), positionCode)) {
                    rowList.add(0, "岗位编号不匹配");
                    errList.add(rowList);
                    return;
                }
                if (!Objects.equals(Optional.ofNullable(position.getPositionName()).orElse(""), positionName)) {
                    rowList.add(0, "岗位名称与编号不匹配");
                    errList.add(rowList);
                    return;
                }

                // 验证招聘数量
                Integer positionNum;
                if (StrUtil.isEmptyIfStr(rowList.get(5).toString().trim())) {
                    rowList.add(0, "招聘数量不能为空");
                    errList.add(rowList);
                    return;
                }
                try {
                    positionNum = Integer.parseInt(rowList.get(5).toString().trim());
                    if (positionNum <= 0) {
                        rowList.add(0, "招聘数量必须大于0");
                        errList.add(rowList);
                        return;
                    }
                } catch (NumberFormatException e) {
                    rowList.add(0, "招聘数量格式错误，必须为整数");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitStartPosition startPosition = new HrmRecruitStartPosition();
                startPosition.setPlanId(plan.getPlanId());
                startPosition.setRecordId(record.getRecordId());
                startPosition.setPositionId(position.getPositionId());
                startPosition.setPositionNum(positionNum);
                startPosition.setPositionDuty(StrUtil.isEmptyIfStr(rowList.get(6)) ? null : rowList.get(6).toString().trim());
                startPosition.setConditionRequire(StrUtil.isEmptyIfStr(rowList.get(7)) ? null : rowList.get(7).toString().trim());
                startPosition.setSalary(StrUtil.isEmptyIfStr(rowList.get(8)) ? null : rowList.get(8).toString().trim());
                startPosition.setWorkLocation(StrUtil.isEmptyIfStr(rowList.get(9)) ? null : rowList.get(9).toString().trim());
                startPosition.setContactUser(StrUtil.isEmptyIfStr(rowList.get(10)) ? null : rowList.get(10).toString().trim());
                startPosition.setContactPhone(StrUtil.isEmptyIfStr(rowList.get(11)) ? null : rowList.get(11).toString().trim());
                startPosition.setCreateTime(LocalDateTime.now());
                addStartPositionList.add(startPosition);
            } else {
                if (rowIndex == 1) {
                    rowList.add(0, "错误信息");
                }
                errList.add(Convert.toInt(rowIndex), rowList);
            }
        });

        if (!addStartPositionList.isEmpty()) {
            this.saveBatch(addStartPositionList);
        }
        FileUtil.del(filePath);
        JSONObject result = new JSONObject().fluentPut("totalSize", num.get()).fluentPut("errSize", 0);
        int listSize = 2;
        if (errList.size() > listSize) {
            File errFile = FileUtil.file("excelData/" + IdUtil.simpleUUID() + ".xlsx");
            BigExcelWriter writer = ExcelUtil.getBigWriter(errFile);
            // 取消数据的黑色边框以及数据左对齐
            CellStyle cellStyle = writer.getCellStyle();
            cellStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
            cellStyle.setBorderTop(BorderStyle.NONE);
            cellStyle.setBorderBottom(BorderStyle.NONE);
            cellStyle.setBorderLeft(BorderStyle.NONE);
            cellStyle.setBorderRight(BorderStyle.NONE);
            cellStyle.setAlignment(HorizontalAlignment.LEFT);
            Font defaultFont = writer.createFont();
            defaultFont.setFontHeightInPoints((short) 11);
            cellStyle.setFont(defaultFont);
            // 取消数字格式的数据的黑色边框以及数据左对齐
            CellStyle cellStyleForNumber = writer.getStyleSet().getCellStyleForNumber();
            cellStyleForNumber.setBorderTop(BorderStyle.NONE);
            cellStyleForNumber.setBorderBottom(BorderStyle.NONE);
            cellStyleForNumber.setBorderLeft(BorderStyle.NONE);
            cellStyleForNumber.setBorderRight(BorderStyle.NONE);
            cellStyleForNumber.setAlignment(HorizontalAlignment.LEFT);
            cellStyleForNumber.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
            cellStyleForNumber.setFont(defaultFont);

            CellStyle textStyle = writer.getWorkbook().createCellStyle();
            DataFormat format = writer.getWorkbook().createDataFormat();
            textStyle.setDataFormat(format.getFormat("@"));

            writer.merge(errList.get(1).size() + 1, errList.get(0).get(0).toString().trim(), true);
            writer.getHeadCellStyle().setAlignment(HorizontalAlignment.LEFT);
            writer.getHeadCellStyle().setWrapText(true);
            Font headFont = writer.createFont();
            headFont.setFontHeightInPoints((short) 11);
            writer.getHeadCellStyle().setFont(headFont);
            writer.getHeadCellStyle().setFillPattern(FillPatternType.NO_FILL);
            writer.getOrCreateRow(0).setHeightInPoints(120);
            writer.setRowHeight(-1, 20);

            for (int i = 0; i < errList.get(1).size(); i++) {
                writer.getSheet().setDefaultColumnStyle(i, textStyle);
            }
            errList.remove(0);
            writer.write(errList);
            writer.close();
            //将错误信息的excel保存七天 604800 七天的秒数
            MultipartFile multipartFile = MultipartFileUtil.getMultipartFile(errFile);
            UploadEntity uploadEntity = adminFileService.uploadTempFile(multipartFile, IdUtil.simpleUUID()).getData();

            redis.setex(AdminCacheKey.UPLOAD_EXCEL_MESSAGE_PREFIX + "file:" + uploadEntity.getFileId(), 604800, uploadEntity.getPath());

            result.fluentPut("errSize", errList.size() - 1).fluentPut("token", uploadEntity.getFileId());
        }
        return result;
    }

    @Override
    public UploadEntity uploadTempFile(MultipartFile file, String batchId) {
        Result<UploadEntity> result = adminFileService.uploadTempFile(file, batchId);
        return result.getData();
    }

}
